#include <stdint.h>
#include <stdio.h>
#include "bpf.h"

int bpf(int cmd, union bpf_attr *attrs)
{
  return syscall(__NR_bpf, cmd, attrs, sizeof(*attrs));
}

int map_create(int val_size, int max_entries)
{
  union bpf_attr attr = {
      .map_type = BPF_MAP_TYPE_ARRAY,
      .key_size = sizeof(int),
      .value_size = val_size,
      .max_entries = max_entries};
  int mapfd = bpf(BPF_MAP_CREATE, &attr);
  if (mapfd == -1)
    perror("bpf(BPF_MAP_CREATE)");
  return mapfd;
}

int map_update(int mapfd, int key, void *pval)
{
  union bpf_attr attr = {
      .map_fd = mapfd,
      .key = (uint64_t)&key,
      .value = (uint64_t)pval,
      .flags = BPF_ANY};
  int res = bpf(BPF_MAP_UPDATE_ELEM, &attr);
  if (res == -1)
    perror("bpf(BPF_MAP_UPDATE_ELEM)");
  return res;
}

int map_lookup(int mapfd, int key, void *pval)
{
  union bpf_attr attr = {
      .map_fd = mapfd,
      .key = (uint64_t)&key,
      .value = (uint64_t)pval,
      .flags = BPF_ANY};
  return bpf(BPF_MAP_LOOKUP_ELEM, &attr);
}